package com.yimi.yinhepda.views.offline.load;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.pda.ym.base.BaseActivity;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.db.dao.ScanDetailVoDao;
import com.yimi.yinhepda.db.dao.UnloadScanTableDao;
import com.yimi.yinhepda.db.dao.UnloadTaskTableDao;
import com.yimi.yinhepda.db.table.ScanDetailVo;
import com.pda.ym.db.table.UnloadScanTable;
import com.yimi.yinhepda.db.table.UnloadTaskTable;
import com.yimi.yinhepda.entity.bean.AddEntity;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.DateHelper;
import com.pda.uce.commom.util.LogUtil;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 离线装车扫描，手动添加界面
 *
 * @author 000432
 */
public class OffLineAddActivity extends BaseActivity {
    private TextView num, piao;
    private EditText intputWaybill;
    private List<AddEntity> dataList = new ArrayList<>();
    private List<ScanDetailVo> scanList;
    private MyAdapter myAdapter;
    private ListView listView;
    private UnloadScanTableDao mUnloadScanTableDao;
    private ScanDetailVoDao scanDetailVoDao;
    private UnloadTaskTableDao taskTableDao;
    private int operTypeCode = 3;
    private String mDeptCode, mDeptName, lineType, offlineTaskNo, toCompany;
    private String userCode;
    /**
     * 配载单对象
     */
    private UnloadTaskTable taskTable;
    /**
     * 本地任务序号
     */
    private Integer order;
    private String platformNo;
    private String joinUserName;
    private String joinWrokNum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_off_line_add);
        initView();
        initData();
    }

    private void initData() {
        userCode = sharedPreferUtil.getValue(Common.USER_CODE);
        mUnloadScanTableDao = new UnloadScanTableDao();
        taskTableDao = new UnloadTaskTableDao();
        scanDetailVoDao = new ScanDetailVoDao();
        //上个界面的配载单号
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            offlineTaskNo = extras.getString("offlineTaskNo");
            mDeptCode = extras.getString("mDeptCode");
            mDeptName = extras.getString("mDeptName");
            lineType = extras.getString("lineType");
            toCompany = extras.getString("toCompany");
            platformNo = extras.getString("platformNo");
            joinUserName = extras.getString("joinUserName");
            joinWrokNum = extras.getString("joinWrokNum");
        } else {
            offlineTaskNo = "";
        }
        //上个界面的列表数据
        scanList = scanDetailVoDao.getDataByStowageAndType(offlineTaskNo, operTypeCode, userCode);
        if (scanList == null) {
            scanList = new ArrayList<>();
        } else {
            List<UnloadTaskTable> stowage = taskTableDao.findStowage(offlineTaskNo, userCode);
            taskTable = stowage.get(0);
        }

        myAdapter = new MyAdapter(this, dataList);
        listView.setAdapter(myAdapter);
        //设置未上传数
        num.setText((int) mUnloadScanTableDao.queryCount("isUpload", 0, operTypeCode, userCode) + "");
    }

    private void initView() {
        ((TextView) findViewById(R.id.title)).setText("手动添加单号");
        num =  findViewById(R.id.num);
        piao =  findViewById(R.id.manaul_add_count);
        intputWaybill =  findViewById(R.id.load_addchildwaybill_ed);
        listView = ( findViewById(R.id.add_chidlwaybill_listview));

        findViewById(R.id.manual_add_btn).setOnClickListener(this);
        findViewById(R.id.add_childwaybill_ok).setOnClickListener(this);
        findViewById(R.id.add_childwaybill_cancle).setOnClickListener(this);
    }

    public OffLineAddActivity() {
        super(true);
    }

    @Override
    public String getPageName() {
        return "离线装车手动添加";
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.manual_add_btn:
                doScan(intputWaybill.getText().toString(), 2);
                break;
            case R.id.add_childwaybill_ok:
                addComplete();
                break;
            case R.id.add_childwaybill_cancle:
                addComplete();
                break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        addComplete();
    }

    @Override
    protected void handleBarCode(String result) {
        super.handleBarCode(result);
        intputWaybill.setText(result);
        //关闭扫描
        setScannerEnabled(false);
        doScan(result, 1);
    }

    private void doScan(String result, int inputType) {
        if (!StringUtils.isWaybillNo(result)) {
            showToast("运单号错误!");
            //开启扫描
            setScannerEnabled(true);
            SoundVibratorManager.playSound(2);
            return;
        }
        //处理扫描
        boolean isInclude = false;
        if (scanList != null && !scanList.isEmpty()) {
            for (int i = 0; i < scanList.size(); i++) {
                //如果在列表中
                if (scanList.get(i).getWaybillNo().equals(result.substring(0, 12))) {
                    //同任务的子单号
                    List<UnloadScanTable> childWaybillNo = mUnloadScanTableDao.getChildWaybillNo(offlineTaskNo, operTypeCode, userCode, result);
                    if (childWaybillNo != null && !childWaybillNo.isEmpty()) {
                        showToast( "运单号重复扫描");
                        //开启扫描
                        setScannerEnabled(true);
                        SoundVibratorManager.playSound(2);
                        return;
                    }
                    //更新列表内容
                    ScanDetailVo scanDetailVo = scanList.get(i);
                    scanDetailVo.setQuantity(scanDetailVo.getQuantity() + 1);
                    scanDetailVo.setScanTime(DateHelper.getDateFormateOffline());
                    //保存运单
                    UnloadScanTable unloadScanTable = saveWaybill(result, inputType);
                    //更新配载单件数
                    taskTable.setPiecesNum(taskTable.getPiecesNum() + 1);
                    try {
                        scanDetailVoDao.update(scanDetailVo);
                        taskTableDao.update(taskTable);
                        mUnloadScanTableDao.insert(unloadScanTable);
                    } catch (SQLException e) {
                        LogUtil.e(e.toString());
                    }
                    isInclude = true;
                    break;
                }
            }
        } else {
//            int count = (int) mUnloadScanTableDao.queryCount("isUpload", 0, operTypeCode, userCode);
//            if (count > 9) {
//                showToast( "你的离线任务很多啊，兄弟");
//                //开启扫描
//                setScannerEnabled(true);
//                SoundVibratorManager.playSound(2);
//                return;
//            }

            //同样始发站-目的站-日期条件下，的order
            if (order == null || order == 0) {
                order = taskTableDao.findByTime(DateHelper.getDateFormateShort(new Date()), sharedPreferUtil.getDeptCode(), mDeptCode, userCode);
                order = order == null ? 1 : order + 1;
            }
            if (offlineTaskNo == null || offlineTaskNo.equals("")) {
                offlineTaskNo = "Z" + DateHelper.getDateTimeFormateForSimple4(new Date()) + mDeptCode + order;
            }
            boolean isNull = false;
            if (taskTable == null) {
                isNull = true;
                //创建配载单
                taskTable = new UnloadTaskTable();
            }
            taskTable.setCreateTime(Constants.getCurrentTimeFormat1());
            taskTable.setShowTime(DateHelper.getDateFormateShort(new Date()));
            //目的站code
            taskTable.setDestDeptCode(mDeptCode);
            //目的站名称
            taskTable.setDestDeptName(mDeptName);
            //始发站code
            taskTable.setSrcDeptCode(sharedPreferUtil.getDeptCode());
            //始发站名称
            taskTable.setSrcDeptName(sharedPreferUtil.getValue(Common.DEPT_NAME));
            // 序号
            taskTable.setOrder(order);
            //操作员工
            taskTable.setOperEmpCode(userCode);
            //干线，支线
            taskTable.setBizTypeCode(Integer.parseInt(lineType));
            //离线号
            taskTable.setOfflineTaskNo(offlineTaskNo);
            //件数
            taskTable.setPiecesNum(1);
            //票数
            taskTable.setPriceNum(1);
            taskTable.setToCompCode(toCompany);
            taskTable.setStatus(0);
            try {
                if (isNull) {
                    taskTableDao.insert(taskTable);
                } else {
                    taskTableDao.update(taskTable);
                }
            } catch (SQLException e) {
                LogUtil.e(e.toString());
            }
        }
        //主单不在列表中
        if (!isInclude) {
            ScanDetailVo scanDetail = new ScanDetailVo();
            scanDetail.setWaybillNo(result.substring(0, 12));
            scanDetail.setInputType(1);
            scanDetail.setQuantity(1);
            scanDetail.setScanTime(DateHelper.getDateFormateOffline());
            scanDetail.setCreateTime(Constants.getCurrentTimeFormat1());
            scanDetail.setOfflineTaskNo(offlineTaskNo);
            scanDetail.setOperTypeCode(operTypeCode);
            scanDetail.setOperEmpCode(userCode);
            //更新列表
            scanList.add(scanDetail);
            //保存运单
            UnloadScanTable unloadScanTable = saveWaybill(result, inputType);
            try {
                //不在列表中，更新件数（但是首次的时候，不走这个逻辑）
                if (scanList.size() > 1) {
                    taskTable.setPiecesNum(taskTable.getPiecesNum() + 1);
                    taskTable.setPriceNum(taskTable.getPriceNum() + 1);
                    taskTableDao.update(taskTable);
                }
                scanDetailVoDao.insert(scanDetail);
                mUnloadScanTableDao.insert(unloadScanTable);
            } catch (SQLException e) {
                LogUtil.e(e.toString());
            }
        }
        //开启扫描
        setScannerEnabled(true);
        SoundVibratorManager.playSound(1);
        //更新显示信息
        dataList.add(new AddEntity(result, result));
        myAdapter.notifyDataSetChanged();
        //设置总票，总件数
        if (dataList != null) {
            piao.setText(String.valueOf(dataList.size()));
        }
        //设置未上传数
        num.setText((int) mUnloadScanTableDao.queryCount("isUpload", 0, operTypeCode, userCode) + "");
    }

    /**
     * 保存运单
     *
     * @param result 扫描到的子单号
     * @param type   输入类型；手动或扫描
     * @return 运单实体
     */
    private UnloadScanTable saveWaybill(String result, int type) {

        UnloadScanTable unloadScan = new UnloadScanTable();
        //时间
        unloadScan.setScanTime(Constants.getCurrentTimeFormat1());
        // 子单
        unloadScan.setChildWaybillNo(result);
        // 主单
        unloadScan.setWaybillNo(result.substring(0, 12));
        // 扫描类型
        unloadScan.setInputType(type);
        // 操作类型
        unloadScan.setOperTypeCode(operTypeCode);
        // 配载单号
        unloadScan.setOfflineTaskNo(offlineTaskNo);
        unloadScan.setOperEmpCode(userCode);
        //设置月台号
        unloadScan.setPlatformNo(platformNo);
        //装卸组参与人
        unloadScan.setOperPersonNames(joinUserName);
        unloadScan.setOperPersonCodes(joinWrokNum);
        return unloadScan;
    }

    /**
     * 手动添加界面，返回扫描界面
     */
    private void addComplete() {
        Bundle bundle = new Bundle();
        bundle.putString("offlineTaskNo", offlineTaskNo);
        setResult(RESULT_OK, this.getIntent().putExtras(bundle));
        finish();
    }

    static class MyAdapter extends BaseAdapter {
        private Context context;
        private List<AddEntity> dataList;

        public MyAdapter(Context context, List<AddEntity> dataList) {
            this.context = context;
            this.dataList = dataList;
        }

        @Override
        public int getCount() {
            return dataList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            MyHolder mHolder;
            if (convertView == null) {
                mHolder = new MyHolder();
                convertView = LayoutInflater.from(context).inflate(R.layout.off_line_add_item, null);
                mHolder.sequencyNum =  convertView.findViewById(R.id.sequencynum);
                mHolder.waybillNum =  convertView.findViewById(R.id.waybillnum);
                convertView.setTag(mHolder);
            } else {
                mHolder = (MyHolder) convertView.getTag();
            }
            mHolder.sequencyNum.setText(position + 1 + "");
            mHolder.waybillNum.setText(dataList.get(position).getWaybillNum());

            return convertView;
        }
    }

    static class MyHolder {
        TextView sequencyNum;
        TextView waybillNum;
    }
}
